<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Created by JetBrains PhpStorm.
 * User: xx
 * Date: 13-12-12
 * Time: 下午5:24
 * To change this template use File | Settings | File Templates.
 */

class crontab extends XX_Controller
{
    var $max_order_id; //前日最大order_id
    public function __construct()
    {
        //调用原有的构造函数
        parent::__construct();

        $this->load->library('Schedule');
        $this->load->library('Analyzerorder');
        $this->load->model('work_model', 'workMod');
        $this->load->model('persistence_model', 'persMod');
        $this->load->library('XXCode');
        $this->max_order_id = 2632;
//        $ret = $this->persMod->get_pers_data("max_order_id");
//        if ($ret->get_code() === 0) {
//            $this->max_order_id = $ret->get_data();
//            if ($this->max_order_id < 2632) {
//                $this->max_order_id = 2632;
//            }
//        }
    }

    public function index()
    {
        //  $HUICJ_DB = $this->load->database('huicj', TRUE);

        $this->update_status_soap();
        //$this->update_status($HUICJ_DB);
        // $this->sync($HUICJ_DB);
        $this->sync_soap();
        $this->schedule->refresh();
        $this->schedule->divider();
        $this->schedule->persistence();

        echo date("Y-m-d H:i:s\r\n", time());
    }

    public function  init_order_no()
    {
        $this->persMod->persistence('max_order_id', $this->workMod->get_max_order_id());
        $soap = new SoapClient(null, array('location' => "http://175.102.13.109/open/order.wsdl.php", 'uri' => 'order.wsdl.php'));
        $soap->InitOrderNo();

        $sql = "DELETE FROM xx_work_info WHERE work_id in (select work_id from xx_work where work_status in (0, 1, 2 ,3))";
        $this->db->query($sql);
        $sql = "DELETE FROM `xx_work` WHERE work_status in (0, 1, 2 ,3)";
        $this->db->query($sql);
        $sql = "TRUNCATE TABLE " . XS_PERSISTENCE;
        $this->db->query($sql);
        $sql = "UPDATE `xx_pipeline` SET `pipe_status` = '0'";
        $this->db->query($sql);
    }

    public function update_status_soap()
    {
        $soap = new SoapClient(null, array('location' => "http://175.102.13.109/open/order.wsdl.php", 'uri' => 'order.wsdl.php'));
        $codes = $this->schedule->cl_get_all_codes();
        $where = '';
        if ($codes) {
            $where = " AND order_id in ($codes) ";
        }
        $order_status_tmp = $soap->QueryOrder($where, " order_sn, order_state ");

        $order_status_list = json_decode($order_status_tmp, true);

        foreach ($order_status_list as $state_node) {
            if ($state_node['order_state'] != 10 && $state_node['order_state'] != 20 && $state_node['order_state'] != 50 && $state_node['order_state'] != 60) {
                $this->schedule->update_status($state_node);
            }
        }
    }

    public function update_status(&$HUICJ_DB)
    {
        $codes = $this->schedule->cl_get_all_codes();
        if ($codes) {
            $codes = " WHERE order_id in ($codes) ";

            $rows = FALSE;
            $sql = "SELECT order_sn, order_state FROM hcj_order " . $codes;
            $query = $HUICJ_DB->query($sql);
            if ($query->num_rows() > 0) {
                $rows = $query->result_array();
            }
            if ($rows) {
                foreach ($rows as $state_node) {
                    if ($state_node['order_state'] != 20 && $state_node['order_state'] != 60) {
                        $this->schedule->update_status($state_node);
                    }
                }
            }
        }
    }

    public function sync_soap()
    {
        try {
            $soap = new SoapClient(null, array('location' => "http://175.102.13.109/open/order.wsdl.php", 'uri' => 'order.wsdl.php'));
            //$order_list_tmp = $soap->QueryOrder(" AND order_state in ( 10, 20, 50, 60) ");
            $where = " AND order_state in ( 10, 20, 50, 60) AND store_id = 13 AND order_id >= " . $this->max_order_id;
            $codes = $this->schedule->cl_get_all_codes();
            if ($codes) {
                $where .= " AND o.order_id not in ($codes) ";
            }
            $order_list_tmp = $soap->QueryOrder($where); //, " order_sn "

            $order_list_tmp = '' . str_replace(array(" ", "　", "\t", "\n", "\r"), array("", "", "", "", ""), $order_list_tmp);
            $order_list = json_decode($order_list_tmp, true);

            foreach ($order_list as $order) {
                $data = array();
                $data['work_code'] = $order['order_sn'];
                $data['order_id'] = $order['order_id'];
                $data['order_time'] = $order['add_time'];
                $data['order_message'] = $order['order_message'];
                $data['buyer_name'] = $order['address']['true_name'];
                $data['phone'] = $order['address']['mob_phone'];
                $data['market'] = $order['market'];
                $data['send_time_point'] = $order['send_time_point1'];
                $data['order_addr'] = $order['address']['area_info'] . $order['address']['address'];
                $specs = array();
                foreach ($order['order_goods'] as $goods) {
                    $specs[] = array(
                        'wi_title' => $goods['goods_name'],
                        'wi_spec' => isset($goods['spec_info']) ? $goods['spec_info'] : '',
                        'wi_unit' => isset($goods['goods_unit']) ? $goods['goods_unit'] : '',
                        'wi_num' => $goods['goods_num'],
                        'wi_img' => $goods['goods_image'],
                    );
                }
                $data['spec'] = $specs;
                $data['add_time'] = time();
                $data['work_cyle'] = $this->analyzerorder->limited_time($order, $data['spec']); //起时时长
                $data['work_weight'] = $this->analyzerorder->weight($order, $data['spec']); //起时时长

                if (!$data['spec']) {
                    continue;
                }
                //任务计数器
                $data['work_counter'] = $order['num'];

                $work_id = $this->workMod->add_work($data);
                if ($work_id > 0) {
                    $data['work_id'] = $work_id;
                    $weight = $this->analyzerorder->weight($order, $data['spec']);
                    $this->schedule->wl_add($weight, $this->schedule->wl_create_node(array('node_weight' => $weight, 'node_code' => $order['order_sn'])), $data);
                }
            }
        } catch (SoapFault $e) {
            echo $e->getMessage();
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    public function sync(&$HUICJ_DB)
    {
        $codes = $this->schedule->cl_get_all_codes();
        if ($codes) {
            $codes = " AND o.order_id not in ($codes) ";
        }
        $rows = FALSE;
        $sql = "SELECT o.order_id, o.order_sn, o.order_state, o.order_message, o.add_time, o.market, o.send_time_point, oa.true_name, oa.area_info, oa.address, oa.tel_phone, oa.mob_phone FROM hcj_order o, hcj_order_address oa WHERE (o.order_state = 20 OR o.order_state = 60) AND o.order_id = oa.order_id $codes ORDER BY o.add_time ASC;";
        log_message('user', $sql);
        $query = $HUICJ_DB->query($sql);
        if ($query->num_rows() > 0) {
            $rows = $query->result_array();
        }

        $data = array();
        foreach ($rows as $order) {
            $data = array();
            $data['work_code'] = $order['order_sn'];
            $data['order_id'] = $order['order_id'];
            $data['order_time'] = $order['add_time'];
            $data['order_message'] = $order['order_message'];
            $data['buyer_name'] = $order['true_name'];
            $data['phone'] = $order['mob_phone'] ? $order['mob_phone'] : $order['tel_phone'];
            $data['market'] = $order['market'];
            $data['send_time_point'] = $order['send_time_point'];
            $data['order_addr'] = str_replace(array(" ", "　", "\t", "\n", "\r"), array("", "", "", "", ""), $order['area_info']) . $order['address'];
            $data['spec'] = $this->get_spec($HUICJ_DB, $order['order_id']);
            $data['add_time'] = time();
            $data['work_cyle'] = $this->analyzerorder->limited_time($order, $data['spec']); //起时时长
            $data['work_weight'] = $this->analyzerorder->weight($order, $data['spec']); //起时时长

            if (!$data['spec']) {
                continue;
            }
            //任务计数器
            $data['work_counter'] = $this->xxcode->get_code('WORKCOUNTER', null);

            $work_id = $this->workMod->add_work($data);
            if ($work_id > 0) {
                $data['work_id'] = $work_id;
                $weight = $this->analyzerorder->weight($order, $data['spec']);
                $this->schedule->wl_add($weight, $this->schedule->wl_create_node(array('node_weight' => $weight, 'node_code' => $order['order_sn'])), $data);
            }
        }

    }

    private function get_spec(&$HUICJ_DB, $order_id)
    {
        $rows = FALSE;
        $sql = "SELECT g.short_goods_name, g.goods_name, gs.spec_goods_spec, gs.spec_name, og.goods_num, g.goods_image FROM hcj_order_goods og, hcj_goods g, hcj_goods_spec gs WHERE og.goods_id = g.goods_id AND og.spec_id = gs.spec_id AND og.order_id = $order_id;";
        $query = $HUICJ_DB->query($sql);
        if ($query->num_rows() > 0) {
            $rows = $query->result_array();
        }
        $specs = array();
        if ($rows) {
            foreach ($rows as $spec_node) {
                $node = array();
                $node['wi_title'] = $spec_node['short_goods_name'] ? $spec_node['short_goods_name'] : $spec_node['goods_name']; //品名
                $goods_unit = ''; //单位
                $spec = ''; //规格
                if (!empty($spec_node['spec_goods_spec']) && !empty($spec_node['spec_name'])) {
                    $spec_name = unserialize($spec_node['spec_name']);
                    if (!empty($spec_name)) {
                        $spec_name = array_values($spec_name);
                        $spec_goods_spec = unserialize($spec_node['spec_goods_spec']);
                        $i = 0;
                        foreach ($spec_goods_spec as $speck => $spec_v) {
                            if ($spec_name[$i] == '单位') {
                                $goods_unit = $spec_v;
                            } else {
                                $spec .= $spec_name[$i] . ':' . $spec_v;
                            }

                            $i++;
                        }
                    }
                }
                $node['wi_spec'] = $spec; //规格
                $node['wi_unit'] = $goods_unit; //单位
                $node['wi_num'] = $spec_node['goods_num']; //>数量
                $node['wi_img'] = $spec_node['goods_image'];

                $specs[] = $node;
            }
        }

        return $specs;
    }
}